package com.example.acroandroiduser;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import ClientCommands.ClientAcroCommand;
import ClientCommands.ClientAnswerCommand;
import ClientCommands.ClientBroadcastCommand;
import ClientCommands.ClientScoreCommand;
import ServerCommands.ServerAnswerCommand;
import ServerCommands.ServerVoteCommand;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableLayout.LayoutParams;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.TextView.OnEditorActionListener;

public class GameScreenActivity extends Activity {

	public Socket s;
	private ObjectInputStream sInput; // to read from the socket
	private ObjectOutputStream sOutput; // to write on the socket
	public boolean stillPlaying = true;
	Point screenRes;
	Display display;
	int screenWidth;
	int screenHeight;
	int round;
	int runTime;
	Timer clocktimer;
	Boolean optionsVisible;
	String acronym;
	String msgToAdd;
	ArrayList<String> answers;
	SoundPool soundPool;
	HashMap<Integer, Integer> soundsMap;
	String name = "ira";
	

	Resources r;

	@SuppressLint("NewApi")
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gamescreen);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		display = getWindowManager().getDefaultDisplay();
		screenRes = new Point();
		optionsVisible = false;
		try {
			display.getSize(screenRes);
			screenWidth = screenRes.x;
			screenHeight = screenRes.y;
		} catch (NoSuchMethodError e) {
			screenWidth = display.getWidth();
			screenHeight = display.getHeight();
		}

		// set text for the acronym textview
		Typeface tf = Typeface.createFromAsset(getAssets(), "FuturaLightBT.ttf");
		TextView tv = (TextView) findViewById(R.id.acro);
		tv.setTypeface(tf);
		TextView tv1 = (TextView) findViewById(R.id.acroResponse);
		tv1.setTypeface(tf);
		TextView tv2 = (TextView) findViewById(R.id.currentTime);
		tv2.setTypeface(tf);
		TextView tv3 = (TextView) findViewById(R.id.roundNumber);
		tv3.setTypeface(tf);
		TextView in = (TextView) findViewById(R.id.instructions);
		in.setTypeface(tf);
		TextView st = (TextView) findViewById(R.id.sent);
		st.setTypeface(tf);
		TextView bd = (TextView) findViewById(R.id.broad);
		bd.setTypeface(tf);
		
		//soundpool
		soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
		
        soundsMap = new HashMap<Integer, Integer>();
        soundsMap.put(1, soundPool.load(this, R.raw.alert, 1));
        soundsMap.put(2, soundPool.load(this, R.raw.clock, 1));

		// set up clockTImer. It is used for running the clock in the corner of
		// the screen. This does not handle the clock animation.
		clocktimer = new Timer();

		// run the clock timer as a test.
		// runClock(60);

		// this generator is just for testing purposes. In normal game the
		// acronym will be generated by the server.
		/*
		 * Random generator = new Random(); String acro = ""; for (int i = 0; i
		 * < 4; i++) { acro = acro +
		 * String.valueOf(Character.toChars((generator.nextInt(25)) + 65)); }
		 * tv.setText(acro);
		 */

		/*
		 * add listeners to to the editText box for getting answers. The
		 * TextWatcher is called every time text changes in the box and handles
		 * updating thetextView under the acronym. The OnTouchListener is called
		 * every time the edittext box is selected and alters the entire view so
		 * only the acronym andline under the acronym are visible. The
		 * EditorActionListener is called when the 'done' button is hit on the
		 * keyboard and makes all the invisible items,visible. The 'back' button
		 * is handled by the ChatEditText object.
		 */
		EditText aet = (EditText) findViewById(R.id.answerInput);
		aet.addTextChangedListener(new AnswerTextWatcher());
		aet.setOnTouchListener(new AnswerTouch());
		aet.setOnEditorActionListener(new AnswerEditor());

		/*
		 * add listeners to to the editText box for entering chat. The
		 * OnTouchListener is called every time the edittext box is selected and
		 * alters the entire viewso only the chatbox is visible. The
		 * EditorActionListener is called when the 'done' button is hit on the
		 * keyboard and makes all the invisible items,visible. The 'back' button
		 * is handled by the ChatEditText object.
		 */

		// r is used for converting pixels to dp
		r = this.getResources();

		new NetworkingThread().execute("");

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.game_screen, menu);
		return true;
		
	}
	
	public void playSound(int sound) {
        AudioManager mgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
        float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        float volume = streamVolumeCurrent / streamVolumeMax; 
 
        soundPool.play(soundsMap.get(sound), volume, volume, 1, 0, 1.0f);
   }
	
	public void optionTrigger(View view) {
		if(optionsVisible){
			Button bt = (Button) findViewById(R.id.chat);
			bt.setVisibility(View.GONE);
			Button bt2 = (Button) findViewById(R.id.score);
			bt2.setVisibility(View.GONE);
			Button bt3 = (Button) findViewById(R.id.exitRoom);
			bt3.setVisibility(View.GONE);
			optionsVisible = false;
			
		}else{
			Button bt = (Button) findViewById(R.id.chat);
			bt.setVisibility(View.VISIBLE);
			Button bt2 = (Button) findViewById(R.id.score);
			bt2.setVisibility(View.VISIBLE);
			Button bt3 = (Button) findViewById(R.id.exitRoom);
			bt3.setVisibility(View.VISIBLE);
			optionsVisible = true;
		}
	}

	public void sendAnswer(View view) {
		EditText ed = (EditText) findViewById(R.id.answerInput);
		if (!(ed.getText().toString().equals(""))) {
			try {
				Log.i("Log_info", "Sending answer");
				sOutput.writeObject(new ServerAnswerCommand(name, ed.getText()
						.toString()));
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
		
		TextView st = (TextView) findViewById(R.id.sent);
		st.setVisibility(View.VISIBLE);
		final Animation out = new AlphaAnimation(1.0f, 0.0f);
		out.setDuration(3000);
		st.startAnimation(out);
		st.setVisibility(View.INVISIBLE);
	}

	public void addStringToAnswerList(String s) {
		TableLayout tl = (TableLayout) findViewById(R.id.answerTable);
		Typeface tf = Typeface.createFromAsset(getAssets(), "berlinSans.ttf");
		TableRow row = new TableRow(this);
		// create the textview to add to the tableview
		TextView tv = new TextView(this);
		tv.setTextColor(getResources().getColor(R.color.acrogreen));
		tv.setText(setAcroResponse(s), BufferType.SPANNABLE);
		tv.setTextSize(40);
		tv.setTypeface(tf);
		tv.setOnClickListener(new AnswerClickListener());
		// convert 100 pixels to dp
		DisplayMetrics mDisplayMetrics = this.getResources()
				.getDisplayMetrics();
		tv.setMaxWidth(mDisplayMetrics.widthPixels - 95);
		// add to tablelayout
		row.addView(tv);
		tl.addView(row, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
	}
	
	public void broadcast(String msg){
		TextView st = (TextView) findViewById(R.id.broad);
		st.setText(msg);
		st.setVisibility(View.VISIBLE);
		final Animation out = new AlphaAnimation(1.0f, 0.0f);
		out.setDuration(3000);
		st.startAnimation(out);
		st.setVisibility(View.INVISIBLE);
	}

	public void addStringToScoreList(String s) {
		String[] strs = s.split("&/&");
		TableLayout tl = (TableLayout) findViewById(R.id.scoreTable);
		Typeface tf = Typeface.createFromAsset(getAssets(), "berlinSans.ttf");
		DisplayMetrics mDisplayMetrics = this.getResources()
				.getDisplayMetrics();
		TableRow row = new TableRow(this);
		
		// create the textview for name to add to the tableview
		TextView tv = new TextView(this);
		tv.setTextColor(getResources().getColor(R.color.acrogreen));
		tv.setText(strs[0]);
		tv.setTextSize(20);
		tv.setTypeface(tf);
		tv.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
		tv.setBackgroundResource(R.drawable.tableborders);
		tv.setWidth(mDisplayMetrics.widthPixels-800);
		tv.setHeight(mDisplayMetrics.heightPixels-1800);
		// add to tablelayout
		row.addView(tv);
		
		// create the textview for answer to add to the tableview
		TextView tv1 = new TextView(this);
		tv1.setTextColor(getResources().getColor(R.color.acroblue));
		tv1.setText(strs[1]);
		tv1.setTextSize(15);
		tv1.setTypeface(tf);
		tv1.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
		tv1.setBackgroundResource(R.drawable.tableborders);
		tv1.setWidth(mDisplayMetrics.widthPixels-500);
		tv1.setHeight(mDisplayMetrics.heightPixels-1800);
		//tv1.setMaxWidth(mDisplayMetrics.widthPixels - 80);
		// add to tablelayout
		row.addView(tv1);
		
		// create the textview for roudn score to add to the tableview
		TextView tv2 = new TextView(this);
		tv2.setTextColor(getResources().getColor(R.color.acroblue));
		tv2.setText(strs[2]);
		tv2.setTextSize(20);
		tv2.setTypeface(tf);
		tv2.setHeight(mDisplayMetrics.heightPixels-1800);
		tv2.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
		tv2.setBackgroundResource(R.drawable.tableborders);
		tv2.setWidth(mDisplayMetrics.widthPixels-1000);
		
		//tv2.setMaxWidth(mDisplayMetrics.widthPixels - 20);
		// add to tablelayout
		row.addView(tv2);
		
		// create the textview for roudn score to add to the tableview
		TextView tv3 = new TextView(this);
		tv3.setTextColor(getResources().getColor(R.color.acroblue));
		tv3.setText(strs[3]);
		tv3.setTextSize(20);
		tv3.setTypeface(tf);
		tv3.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL);
		tv3.setHeight(mDisplayMetrics.heightPixels-1800);
		//tv3.setMaxWidth(mDisplayMetrics.widthPixels - 20);
		// add to tablelayout
		row.addView(tv3);
		
		tl.addView(row, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.WRAP_CONTENT));
	}

	public SpannableString setAcroResponse(String msg) {
		msg = msg.trim();
		SpannableString text = new SpannableString(" ");
		int counter = msg.split(" ").length;
		int locCount = 1;
		if (msg.length() > 0) {
			text = new SpannableString(msg);
			for (int i = 0; i < counter; i++) {
				if (i == 0) {
					if (msg.toUpperCase().charAt(0) == acronym.charAt(0)) {
						text.setSpan(new ForegroundColorSpan(getResources()
								.getColor(R.color.acroblue)), 0, 1, 0);
					} else {
						text.setSpan(new ForegroundColorSpan(getResources()
								.getColor(R.color.acropink)), 0, 1, 0);
					}
				} else if (i < acronym.length()) {
					int loc = msg.indexOf(" ", locCount) + 1;
					if (msg.toUpperCase().charAt(loc) == acronym.charAt(i)) {
						text.setSpan(new ForegroundColorSpan(getResources()
								.getColor(R.color.acroblue)), loc, loc + 1, 0);
					} else {
						text.setSpan(new ForegroundColorSpan(getResources()
								.getColor(R.color.acropink)), loc, loc + 1, 0);
					}
					locCount = loc;
				}
			}
		}
		return text;
	}

	/*
	 * Runs the thread that alters the clock. This does not handle the clock
	 * animation
	 */
	public void runClock(int startTime, boolean sound) {
		// First make sure no other clockTask is running.

		clocktimer.cancel();
		clocktimer.purge();
		clocktimer = new Timer();
		// Run clockTask.
		clocktimer.schedule(new clockTask(startTime, sound), 0, 1000);
	}

	private class NetworkingThread extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			try {
				Log.i("Log_info", "Trying to Connect");
				s = new Socket("192.168.1.2", 280);

				Log.i("Log_info", "Connected");
				sInput = new ObjectInputStream(s.getInputStream());
				sOutput = new ObjectOutputStream(s.getOutputStream());
				Log.i("Log_info", "Streams Made");
				sOutput.writeObject(name);
				Log.i("Log_info", "Name sent");
				sOutput.flush();

			} catch (Exception e) {
				Log.i("Log_info", e.getMessage());
			}

			while (stillPlaying) {
				Object o;
				try {
					o = sInput.readObject();
					Log.i("Log_info", "Object received");
					if (o instanceof ClientBroadcastCommand) {
						broadcast(((ClientBroadcastCommand) o).getMessage());
					} else if (o instanceof ClientAcroCommand) {
						Log.i("Log_info", "ClientAcroCommand - "
								+ ((ClientAcroCommand) o).getAcro());
						acronym = ((ClientAcroCommand) o).getAcro();
						round = ((ClientAcroCommand) o).getRound();
						runTime = ((ClientAcroCommand) o).getTime();
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								TextView tv = (TextView) findViewById(R.id.acro);
								tv.setVisibility(View.VISIBLE);
								TextView tv1 = (TextView) findViewById(R.id.acroResponse);
								tv1.setVisibility(View.VISIBLE);
								EditText et = (EditText) findViewById(R.id.answerInput);
								et.setVisibility(View.VISIBLE);
								et.setText("");
								Button bt = (Button) findViewById(R.id.sendAnswer);
								bt.setVisibility(View.VISIBLE);
								TableLayout tl = (TableLayout) findViewById(R.id.answerTable);
								tl.setVisibility(View.GONE);
								TableLayout tl2 = (TableLayout) findViewById(R.id.scoreTable);
								tl2.setVisibility(View.GONE);
								tv.setText(acronym);
								TextView rn = (TextView) findViewById(R.id.roundNumber);
								rn.setText("Round " + round + "/10");
								TextView in = (TextView) findViewById(R.id.instructions);
								in.setText("Create An Acronym!");
								runClock(runTime, true);
								playSound(1);
							}
						});
					} else if (o instanceof ClientAnswerCommand) {
						Log.i("Log_info", "ClientAnswerCommand Recieved ");
						answers = ((ClientAnswerCommand) o).getAnswers();
						acronym = ((ClientAnswerCommand) o).getAcro();
						round = ((ClientAnswerCommand) o).getRound();
						runTime = ((ClientAnswerCommand) o).getTime();
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								TextView acro = (TextView) findViewById(R.id.acro);
								RelativeLayout.LayoutParams head_params = (RelativeLayout.LayoutParams) acro
										.getLayoutParams();
								head_params.setMargins(0,
										(int) (screenHeight * .09), 0, 0);
								acro.setLayoutParams(head_params);
								acro.setText(acronym);
								TextView tv1 = (TextView) findViewById(R.id.acroResponse);
								tv1.setVisibility(View.GONE);
								EditText et = (EditText) findViewById(R.id.answerInput);
								et.setVisibility(View.GONE);
								Button bt = (Button) findViewById(R.id.sendAnswer);
								bt.setVisibility(View.GONE);
								TableLayout tl2 = (TableLayout) findViewById(R.id.scoreTable);
								tl2.setVisibility(View.GONE);
								TableLayout tl = (TableLayout) findViewById(R.id.answerTable);
								tl.removeAllViews();
								for (String s : answers) {
									addStringToAnswerList(s);
								}
								tl.setVisibility(View.VISIBLE);
								TextView rn = (TextView) findViewById(R.id.roundNumber);
								rn.setText("Round " + round + "/10");
								TextView ct = (TextView) findViewById(R.id.currentTime);
								head_params = (RelativeLayout.LayoutParams) ct
										.getLayoutParams();
								head_params.setMargins(0, 0, 0, 0);
								ct.setLayoutParams(head_params);
								TextView in = (TextView) findViewById(R.id.instructions);
								in.setText("Pick Your Favorite Acronym!");
								runClock(runTime, true);
							}
						});
					} else if (o instanceof ClientScoreCommand) {
						Log.i("Log_info", "ClientScoreCommand Recieved ");
						answers = ((ClientScoreCommand) o).getScores();
						round = ((ClientScoreCommand) o).getRound();
						runTime = ((ClientScoreCommand) o).getTime();
						runOnUiThread(new Runnable() {

							@Override
							public void run() {
								TextView acro = (TextView) findViewById(R.id.acro);
								acro.setVisibility(View.GONE);
								TextView tv1 = (TextView) findViewById(R.id.acroResponse);
								tv1.setVisibility(View.GONE);
								EditText et = (EditText) findViewById(R.id.answerInput);
								et.setVisibility(View.GONE);
								Button bt = (Button) findViewById(R.id.sendAnswer);
								bt.setVisibility(View.GONE);
								TableLayout tl2 = (TableLayout) findViewById(R.id.answerTable);
								tl2.setVisibility(View.GONE);
								TableLayout tl = (TableLayout) findViewById(R.id.scoreTable);
								tl.removeAllViews();
								for (String s : answers) {
									addStringToScoreList(s);
								}
								tl.setVisibility(View.VISIBLE);
								TextView rn = (TextView) findViewById(R.id.roundNumber);
								rn.setText("Round " + round + "/10");
								TextView in = (TextView) findViewById(R.id.instructions);
								in.setText("Next Round Will Start Soon!");
								runClock(runTime, false);
							}
						});
					}
				} catch (Exception e) {
					e.printStackTrace();
				}

			}

			return "done";
		}

		@Override
		protected void onPostExecute(String result) {

		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onProgressUpdate(Void... values) {
		}
	}

	private class AnswerClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {

			TableLayout tl = (TableLayout) findViewById(R.id.answerTable);
			Log.i("Log_info", "Item Clicked - "
					+ ((TextView) v).getText().toString());

			for (int i = 0; i < tl.getChildCount(); i++) {
				TableRow row = (TableRow) tl.getChildAt(i);
				TextView tv = (TextView) row.getChildAt(0);
				if (((TextView) v).getText().toString()
						.equals(tv.getText().toString())) {
					Log.i("Log_info", "To Gold - " + tv.getText().toString());
					tv.setTextColor(getResources().getColor(R.color.Gold));
				} else {
					Log.i("Log_info", "To Green - " + tv.getText().toString());
					tv.setTextColor(getResources().getColor(R.color.acrogreen));

				}
			}

			try {
				sOutput.writeObject(new ServerVoteCommand(((TextView) v)
						.getText().toString()));
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}

		}
	}

	/*
	 * Called when the value on the EditText for inputting an answer changes.
	 * This updates the acronymResponse TextView.
	 */
	public class AnswerTextWatcher implements TextWatcher {

		@Override
		public void afterTextChanged(Editable arg0) {

		}

		@Override
		public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {

		}

		@Override
		public void onTextChanged(CharSequence arg0, int arg1, int arg2,
				int arg3) {
			EditText et = (EditText) findViewById(R.id.answerInput);
			TextView tv = (TextView) findViewById(R.id.acroResponse);
			tv.setText(setAcroResponse(et.getText().toString()),
					BufferType.SPANNABLE);

		}

	}

	/*
	 * Called when EditText to input answer is touched. It adjusts the view so
	 * to prepare for the keyboard. This moves the acronym and acronym response
	 * into place.
	 */
	public class AnswerTouch implements OnTouchListener {

		@Override
		public boolean onTouch(View arg0, MotionEvent arg1) {
			Log.d("Log_info", "Answer Touch - onTouch Called.");
			TextView acro = (TextView) findViewById(R.id.acro);
			RelativeLayout.LayoutParams head_params = (RelativeLayout.LayoutParams) acro
					.getLayoutParams();
			head_params.setMargins(0, (int) (screenHeight * .3), 0, 0);
			acro.setLayoutParams(head_params);
			TextView ct = (TextView) findViewById(R.id.currentTime);
			head_params = (RelativeLayout.LayoutParams) ct.getLayoutParams();
			head_params.setMargins(0, (int) (screenHeight * .25), 0, 0);
			ct.setLayoutParams(head_params);
			return false;
		}

	}

	/*
	 * Called when the 'done' button is hit on the keyboard for the editText for
	 * inputting the answer. adds the chatbox back if it is visible and adds the
	 * chatTrigger back. Finally moves the acronym back to its place.
	 */
	public class AnswerEditor implements OnEditorActionListener {

		@Override
		public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
			Log.d("Log_info", "Answer Editor - onEditor Called. ");
			TextView acro = (TextView) findViewById(R.id.acro);
			RelativeLayout.LayoutParams head_params = (RelativeLayout.LayoutParams) acro
					.getLayoutParams();
			head_params.setMargins(0, (int) (screenHeight * .09), 0, 0);
			acro.setLayoutParams(head_params);
			TextView ct = (TextView) findViewById(R.id.currentTime);
			head_params = (RelativeLayout.LayoutParams) ct.getLayoutParams();
			head_params.setMargins(0, 0, 0, 0);
			ct.setLayoutParams(head_params);
			return false;
		}

	}

	/*
	 * Called when the 'done' button is hit on the keyboard for the send chat
	 * message editText. Edits the view back to normal.
	 */
	public class ChatEditor implements OnEditorActionListener {

		@Override
		public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
			Log.d("Log_info", "Chat Editor - onEditor Called. ");
			TextView tv1 = (TextView) findViewById(R.id.acro);
			tv1.setVisibility(View.VISIBLE);
			tv1.setEnabled(true);
			Button bt = (Button) findViewById(R.id.sendAnswer);
			bt.setVisibility(View.VISIBLE);
			bt.setEnabled(true);
			EditText et = (EditText) findViewById(R.id.answerInput);
			et.setVisibility(View.VISIBLE);
			et.setEnabled(true);
			TextView tv2 = (TextView) findViewById(R.id.acroResponse);
			tv2.setVisibility(View.VISIBLE);
			tv2.setEnabled(true);
			return false;
		}

	}

	/*
	 * this thread is for the game timer. It does not handle the clock
	 * animation.
	 */
	class clockTask extends TimerTask {
		int currentTime;
		boolean sound;

		public clockTask(int startTime, boolean sound) {
			this.currentTime = startTime;
			this.sound = sound;
		}

		public void run() {
			if (currentTime >= 0) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						TextView tv = (TextView) findViewById(R.id.currentTime);
						tv.setText("" + currentTime);
						if(sound && (currentTime == 10 || currentTime == 5)){
							playSound(2);
						}
						currentTime = currentTime - 1;
					}
				});

			} else {

				clocktimer.cancel();
				clocktimer.purge();
			}
		}
	}

}
